package com.xing.thread.ringbuffer;

import java.util.concurrent.atomic.AtomicInteger;

public class RingBuffer {

    private final Data[] buffer;

    private AtomicInteger sequecer = new AtomicInteger();

    private final int DEFAULT_LENGTH = 1024;

    public RingBuffer(int bufferSize) {
        if(!is2XValue(bufferSize)) {
            throw new IllegalArgumentException("bufferSize必须是2的n次方");
        }
        buffer = new Data[bufferSize];
    }

    public RingBuffer() {
        buffer = new Data[DEFAULT_LENGTH];
    }

    public int save(Data data) {
        int next = sequecer.getAndIncrement();
        int index = next & (buffer.length - 1);
        buffer[index] = data;
        return next;
    }

    public Data get(int index) {
        if(index > buffer.length) {
            return null;
        }
        return buffer[index];
    }

    private boolean is2XValue(int value) {
        return value > 0 && (value & (value - 1)) == 0;
    }

}
